package com.kipling.kio.core.task;

import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;

import com.kipling.kio.core.bean.MsgBean;
import com.kipling.kio.core.intf.KioHandler;
import com.kipling.kio.core.intf.Packet;
import com.kipling.kio.json.Json;
import com.kipling.kio.server.ServerGroupContext;

/**
 * 解码
 * 
 * @author 谭耀武
 * 2012-08-09
 * 
 */
public class DecodeRunnable< P extends Packet, R> implements Runnable
{

	
	private ServerGroupContext< P, R> serverGroupContext;

	
	private MsgBean bean = null;

	/**
	 * 
	 */
	public DecodeRunnable(ServerGroupContext< P, R> serverGroupContext)
	{
		this.serverGroupContext = serverGroupContext;
	}

	/**
	 * Handler.
	 *
	 * @param <Ext> the generic type
	 * @param <P> the generic type
	 * @param <R> the generic type
	 * @param ServerGroupContext the channel context
	 * @param packet the packet
	 */
	public static <SessionContext, P extends Packet, R> void handler(ServerGroupContext< P, R> serverGroupContext, P packet, int byteCount)
	{	
		KioHandler<P, R>  handlerRunnable = serverGroupContext.getKioHandler();
		try {
			handlerRunnable.handler(packet,serverGroupContext);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}
	public void setServerGroupContext(ServerGroupContext< P, R> serverGroupContext)
	{
		this.serverGroupContext = serverGroupContext;
	}

	@Override
	public String toString()
	{
		StringBuilder builder = new StringBuilder();
		builder.append(this.getClass().getSimpleName()).append(":");
		builder.append(serverGroupContext.toString());
		return builder.toString();
	}

	/** 
	 * @see java.lang.Runnable#run()
	 * 
	 * @author: tanyaowu
	 * 2017年3月21日 下午4:26:39
	 * 
	 */
	@Override
	public void run()
	{
		ByteBuffer byteBuffer = bean.getByteBuffer();

		try {
			//byteBuffer.flip();
			String received = Charset.forName("utf-8").newDecoder().decode(byteBuffer).toString();			
			if(received==null || "".equals(received)){
				
			}else{
				System.out.println("DecodeRunnable.run:received:"+received);
				Packet packet = Json.toBean(received, Packet.class);
				if(packet!=null && packet.getUserid()!=null){
					serverGroupContext.setSocketChannel(packet.getUserid(), bean.getSocketChannel());
				}
				handler(serverGroupContext, (P)packet, 0);
			}
		} catch (CharacterCodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
	}

	public MsgBean getBean() {
		return bean;
	}

	public void setBean(MsgBean bean) {
		this.bean = bean;
	}

}
